// src/utils/websocket.js
import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

let stompClient = null;

export function connectWebSocket(userName, onMessage) {
    const baseUrl = process.env.VUE_APP_API_BASE_URL;
    const socket = new SockJS(`${baseUrl}/ws`);
    stompClient = new Client({
        webSocketFactory: () => socket,
        reconnectDelay: 5000,
        onConnect: () => {
            // 推荐订阅路径
            const destination = '/user/queue/meeting-notification';
            console.log('WebSocket connected, subscribing to:', destination);
            stompClient.subscribe(destination, (message) => {
                console.log('Raw message:', message);
                console.log('Message body:', message.body);
                if (onMessage) {
                    try {
                        const parsedMessage = JSON.parse(message.body);
                        console.log('Parsed message:', parsedMessage);
                        onMessage(parsedMessage);
                    } catch (error) {
                        console.error('Failed to parse message:', error);
                    }
                }
            });
        },
        onStompError: (frame) => {
            console.error('STOMP error:', frame.headers['message'], frame.body);
        },
        onWebSocketClose: () => {
            console.error('WebSocket connection closed');
        },
        onDisconnect: () => {
            console.log('WebSocket disconnected');
        }
    });
    stompClient.activate();
}

export function disconnectWebSocket() {
    if (stompClient) {
        stompClient.deactivate();
        stompClient = null;
        console.log('WebSocket deactivated');
    }
}
